﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using CsvHelper;
using GMap.NET;
using LeakView.common;
using LeakView.service;

namespace LeakView.view
{
    public partial class FormHistory : Form
    {
        private List<AjaxLeakInfo> CacheLeaks = null;

        public FormHistory()
        {
            InitializeComponent();

            this.viewMapForHistory1.showLeak(null);
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            var url = AnyConfigs.get("APP").get("MainURL").GetOrDefault("http://localhost:8080");

            long start = Tools.ConvertDataTimeToLong(this.dateTimePickerStart.Value);
            long end = Tools.ConvertDataTimeToLong(this.dateTimePickerEnd.Value);

            try
            {
                AnyConfig config = AnyConfigs.get("APP");
                String pairId = config.get("PairId").GetOrDefault("default");

                using (Ajax ajax = new Ajax())
                {
                    var content = AjaxContent.Get()
                        .setUrl(url, "client/history2.do")
                        .AddParameter("pairId", pairId)
                        .AddParameter("startTime", start.ToString())
                        .AddParameter("stopTime", end.ToString());

                    List<AjaxLeakInfo> leaks = ajax.DoPost<List<AjaxLeakInfo>>(content);
                    setLeaks(leaks);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        private void setLeaks(List<AjaxLeakInfo> leaks)
        {
            this.dataGridView1.Rows.Clear();

            this.CacheLeaks = leaks;

            if (leaks != null)
            {
                Console.WriteLine("Get leaks, count=" + leaks.Count);

                leaks.ForEach((leak) =>
                {
                    DateTime dt = Tools.ConvertLongToDateTime(leak.time);

                    PointLatLng pt = PipeModal.ME.GetPosition(leak.location);

                    string ack = "未确认";
                    if (leak.ackTime > 0)
                    {
                        DateTime ackTime = Tools.ConvertLongToDateTime(leak.ackTime);
                        ack = ackTime.ToString() + "|" + leak.ackUser;
                    }


                    int index = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[index].Cells[0].Value = leak.id.ToString();
                    this.dataGridView1.Rows[index].Cells[1].Value = dt.ToString();
                    this.dataGridView1.Rows[index].Cells[2].Value = leak.location.ToString("F3");
                    this.dataGridView1.Rows[index].Cells[3].Value = pt.Lng.ToString() + "," + pt.Lat.ToString();
                    this.dataGridView1.Rows[index].Cells[4].Value = leak.statusStr;
                    this.dataGridView1.Rows[index].Cells[5].Value = ack;
                    this.dataGridView1.Rows[index].Tag = leak;
                });
            }
            else
            {
                Console.WriteLine("No leaks found.");
            }
        }

        public static string ConvertStatusToString(int status)
        {
            switch (status)
            {
                case 0: return "报警";
                case 1: return "修理";
                case 2: return "无效";
                case 3: return "确认";
                case 4: return "区域外";
                case 5: return "无校准";
                default:
                    return "未知:" + status;
            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if(this.dataGridView1.SelectedRows.Count > 0)
            {
                AjaxLeakInfo leak = (AjaxLeakInfo)this.dataGridView1.SelectedRows[0].Tag;
                this.viewMapForHistory1.showLeak(leak);
            }
        }

        private void buttonExport_Click(object sender, EventArgs e)
        {
            ExportCSV.export(this.dataGridView1);
            /*
            if (this.dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("没有可以导出的数据！");
                return;
            }

            var result = this.saveFileDialog.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }

            using (var writer = new StreamWriter(this.saveFileDialog.FileName, false, Encoding.GetEncoding(936)))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                foreach (DataGridViewColumn column in this.dataGridView1.Columns)
                {
                    csv.WriteField(column.HeaderText);
                }
                csv.NextRecord();

                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    for (var i = 0; i < this.dataGridView1.Columns.Count; i++)
                    {
                        csv.WriteField(row.Cells[i].Value.ToString());
                    }
                    csv.NextRecord();
                }
            }
            */

        }
    }
}
